package com.example.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import common.Result;
import entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import request.AdminPageRequest;
import request.LoginRequest;
import request.PasswordRequest;
import request.RegisterRequest;
import com.example.admin.service.IAdminService;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    IAdminService adminService;

    @PostMapping("/login")
    public SaResult login(@RequestBody LoginRequest loginRequest) {

        if (adminService.checkLogin(loginRequest)) {

            StpUtil.login(loginRequest.getId());
        } else {
            return SaResult.error("用户名或密码错误");
        }

        return SaResult.data(StpUtil.getTokenInfo());
    }

    @RequestMapping("/register")
    public SaResult register(@RequestBody RegisterRequest registerRequest) {
        if (adminService.getByUsername(registerRequest.getUsername()) != null) {
            return SaResult.error("用户已存在");
        }
        adminService.save(registerRequest);
        return SaResult.ok();
    }

    @PutMapping("/password")
    public Result password(@RequestBody PasswordRequest request) {
        adminService.changePass(request);
        return Result.success();
    }

    @PostMapping("/save")
    public Result save(@RequestBody RegisterRequest registerRequest) {
        adminService.save(registerRequest);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin obj) {
        adminService.update(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        adminService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Admin obj = adminService.getById(id);
        return Result.success(obj);
    }

    @GetMapping("/list")
    public Result list() {
        List<Admin> list = adminService.list();
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result page(AdminPageRequest pageRequest) {
        return Result.success(adminService.page(pageRequest));
    }





}
